<template>
  <!-- 选择活动报名票种 -->
  <PageContainer>
    <view class="container">
      <Header title="选择报名类型" :default-slot-content-height="250">
        <TopActivityInfo
          :cover-url="activityInfo?.coverUrl"
          :address="activityInfo?.address"
          :address-name="activityInfo?.addressName"
          :start-time="activityInfo?.startTime"
          :title="activityInfo?.title"
          :latitude="activityInfo?.latitude"
          :longitude="activityInfo?.longitude"
          :activity-status="activityInfo?.activityStatus"
        />
      </Header>
      <view class="pa-16">
        <view class="fz-14 gray-color-2 mb-12">
          <text>类型</text>
        </view>
        <template v-for="v in ticketList" :key="v.id">
          <TicketItem
            :item="v"
            :is-select="selectedTicket?.id === v.id"
            @click="handleTicketItemClick(v)"
            @show-no-permission-popup="openModel(v)"
          />
        </template>
      </view>
      <view class="placeholder-view"></view>
      <view class="bottom-view">
        <!-- <view class="px-16 py-12 disFlxJS">
          <view clss="disFlxCC">
            <view class="fz-12 title-color">
              <text>购票数量</text>
            </view>
            <view
              v-if="
                selectedTicket?.ticketStatus === TicketStatusEnum.RUSH_TICKET &&
                selectedTicket.buyLimit === TicketBuyLimitEnum.LIMIT
              "
              class="fz-12"
              style="color: #969799"
            >
              <text>限购{{ selectedTicket?.buyMinNum || 1 }}张起</text>
              <text>，最多{{ selectedTicket?.buyMaxNum }}张</text>
            </view>
          </view>
         
        </view> -->
        <view class="px-16 pt-12 pb-16 disFlxJS">
          <!-- <view class="fw-7" style="width: 55%">
            <template v-if="selectedTicket?.ticketType === TicketTypeEnum.CHARGE">
              <text class="fz-12 price-color">{{ DEFAULT_SYMBOL }}</text>
              <text class="fz-24 price-color">
                {{ totalPrice }}
              </text>
            </template>
            <text v-else-if="selectedTicket?.ticketType === TicketTypeEnum.FREE">
              <text class="fz-24 price-color">免费</text>
            </text>
          </view> -->
          <TButton
            v-if="disabledNextBtn"
            :text="disabledNextBtn"
            type="primary"
            :disabled="true"
            class="gutter-btn"
            custom-class="h-44 linh-44 br-22 px-16"
          />
          <TButton
            v-else
            text="下一步"
            type="primary"
            class="gutter-btn"
            custom-class="h-44 linh-44 br-22 px-16"
            @click="handleNext"
          />
        </view>
      </view>
    </view>
    <UniPopup ref="noPermissionPopupRef" borderRadius="32rpx 32rpx 0 0" backgroundColor="#fff">
      <view class="default-color">
        <view class="disFlxCC pa-16">
          <text class="fz-16 mb-12">报名限制详情</text>
          <text class="fz-14 mb-12">
            您当前身份：{{ cocInfo ? cocInfo.levelName : '普通用户' }}
          </text>
          <text class="fz-14 mb-12" style="color: #646566">当前类型报名需要以下身份：</text>
          <scroll-view
            class="br-8 pa-12 identity-list"
            :enhanced="true"
            :show-scrollbar="false"
            scroll-y
            enable-flex
          >
            <template v-for="(v, i) in identityList" :key="i">
              <view class="identity-tag fz-12 px-8 py-4 br-2 mr-8 mb-8">
                <text>{{ v.memberLevelName }}</text>
              </view>
            </template>
          </scroll-view>
        </view>
        <TButtonGroup position="unset" :styles="{ padding: '20rpx 32rpx' }">
          <TButton
            text="取消"
            type="none"
            class="gutter-btn"
            custom-class="h-44 linh-44 br-22 px-16"
            :custom-style="{
              color: '#2878FF',
              border: '1px solid #2878FF',
              boxSizing: 'content-box',
            }"
            @click="closeModel"
          />
          <TButton
            v-if="!cocInfo"
            text="申请成为会员"
            type="primary"
            class="gutter-btn"
            custom-class="h-44 linh-44 br-22 px-16"
            @click="handleToSelectiveType"
          />
        </TButtonGroup>
      </view>
    </UniPopup>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* selectTicketType 报名购票 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { navigateTo, onLoad } from '@/router';
  import { computed, getCurrentInstance, ref } from 'vue';
  import type { SelectTicketType } from '@/router/types/modules';
  import TicketItem from './components/TicketItem.vue';
  import TopActivityInfo from '../components/TopActivityInfo.vue';
  import { formatMoney, DEFAULT_SYMBOL } from '@/utils/number';
  import { activityticketList } from '@/api/activity';
  import type { IActivityListResData, IActivityTicketResult } from '@/api/activity/types';
  import { TicketBuyLimitEnum, TicketStatusEnum, TicketTypeEnum } from '@/enums/activityStatusEnum';
  import { getBuyMaxNum } from '../components/activity';
  import { onShow } from '@dcloudio/uni-app';
  import { isNumber } from 'lodash-es';
  import { useUserStore } from '@/store/modules/user';
  import { toSelectiveType } from '@/utils/dynamicConfig';
  import { useActivityStore } from '@/store/modules/activity';
  import { Toast } from '@/utils';

  const { cocInfo } = useUserStore();
  const { getActivityOrderRouteParams } = useActivityStore();

  const routingParameters = ref<SelectTicketType>()
  const activityInfo = ref<IActivityListResData>();
  const ticketList = ref<IActivityTicketResult[]>([]);
  const selectedTicket = ref<IActivityTicketResult>();
  const purchaseQuantity = ref<number>(1);

  onLoad<'selectTicketType'>((op) => {
    routingParameters.value = op
    if (getActivityOrderRouteParams) {
      activityInfo.value = getActivityOrderRouteParams;
      getActivityticketList(getActivityOrderRouteParams.id);
    } else {
      Toast('活动数据不能为空');
    }
  });

  onShow(() => {
    if (ticketList.value.length && activityInfo.value) {
      getActivityticketList(activityInfo.value.id);
    }
  });

  function getActivityticketList(id: number) {
    activityticketList(id).then((r) => {
      ticketList.value = r;
    });
  }

  const getMaxNum = computed(() => {
    if (selectedTicket.value) {
      return getBuyMaxNum(selectedTicket.value);
    }

    return 1;
  });

  const totalPrice = computed(() => {
    let money = 0;
    if (selectedTicket.value?.ticketType === TicketTypeEnum.CHARGE) {
      const price = isNumber(selectedTicket.value.discountPrice)
        ? selectedTicket.value.discountPrice
        : selectedTicket.value.price;
      money = price * purchaseQuantity.value;
    }
    return formatMoney({
      money,
      showSymbol: false,
    });
  });

  function handleTicketItemClick(item: IActivityTicketResult) {
    purchaseQuantity.value = item.buyMinNum || 1;
    selectedTicket.value = item;
  }

  const disabledNextBtn = computed(() => {
    if (!selectedTicket.value) return '请选择报名类型';
    const errText = '此类型暂不可购买';
    const { ticketStatus, buyTicket, reason } = selectedTicket.value;
    if (!buyTicket) return reason || errText;
    if (ticketStatus !== TicketStatusEnum.RUSH_TICKET) {
      return errText;
    }
    return '';
  });

  function handleNext() {
    if (routingParameters.value && selectedTicket.value) {
      navigateTo({
        name: 'createActivityRegisterOrder',
        options: {
          ticketId: selectedTicket.value.id,
          selectedQuantity: purchaseQuantity.value,
          ...routingParameters.value,
        },
      });
    }
  }

  function handleToSelectiveType() {
    toSelectiveType(
      {
        linkUrl: 'selectiveType',
        isRedirectTo: true,
      },
      () => {},
      true,
    );
  }

  const _this = getCurrentInstance();
  const identityList = ref<IActivityTicketResult['memberIdentityList']>([]);
  function openModel(item: IActivityTicketResult) {
    identityList.value = item.memberIdentityList;
    (_this?.refs['noPermissionPopupRef'] as any).open('bottom');
  }

  function closeModel() {
    identityList.value = [];
    (_this?.refs['noPermissionPopupRef'] as any).close();
  }
</script>

<style lang="scss" scoped>
  .gray-color-2 {
    color: #646566;
  }

  .title-color {
    color: #333;
  }

  .price-color {
    color: #ea5e0e;
  }

  .bottom-view {
    position: fixed;
    bottom: 0;
    z-index: 99;
    width: 100%;
    background-color: #fff;
    // padding-bottom: constant(safe-area-inset-bottom);
    // padding-bottom: env(safe-area-inset-bottom);
    box-shadow: 0px 4rpx 24rpx 0px rgba(150, 151, 153, 0.16);
  }

  .placeholder-view {
    height: 240rpx;
    // padding-bottom: constant(safe-area-inset-bottom);
    // padding-bottom: env(safe-area-inset-bottom);
  }

  .identity-list {
    width: calc(100% - 64rpx);
    height: 340rpx;
    border: 1px solid #ebedf0;
    .identity-tag {
      display: inline-block;
      color: #2878ff;
      background-color: #d0f7ff;
      width: fit-content;
    }
  }
</style>
